package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.MinIoTemplate;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.thread.WmUserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;


@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private MinIoTemplate minIoTemplate;


    @Override
    public ResponseResult upload(MultipartFile file) throws IOException {

        //获取上传图片的输入流
        InputStream inputStream = file.getInputStream();

        // 调用mino上传接口，进行上传操作
        // 文件名构成：不重复的文件名 + 文件后缀
        // 获取分割之后的后面的那段内容
        String contentType = file.getContentType();
        if (StringUtils.isEmpty(contentType)){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

        //{"image","png"} 后缀名
        String suffixName =  contentType.split("/")[1];
//        String substringName = contentType.substring(contentType.lastIndexOf("/") + 1);
        String fileName = System.currentTimeMillis()+"."+ suffixName;

        //把图片上传到minio
        String url = minIoTemplate.uploadFile("", fileName, inputStream, "image");

        //将上传后的url 写入到数据库 material表
        WmMaterial material = new WmMaterial();
        material.setCreatedTime(new Date());
//        material.setUserId(0);
        //改造 从ThreadLocal中获取userId 关键关键 关键
        material.setUserId(WmUserThreadLocal.get().getId());
        material.setUrl(url);
        material.setIsCollection((short) 0);
        material.setType((short) 0);
        int insertResult = wmMaterialMapper.insert(material);
        if (insertResult<1){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

        return ResponseResult.okResult(material);
    }

    @Override
    public ResponseResult list(WmMaterialDto dto) {
        if(dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Integer page = dto.getPage();
        Integer size = dto.getSize();
        Short isCollection = dto.getIsCollection();

        // 构造查询条件
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();

        // 是否收藏
        wrapper.eq(isCollection != null && isCollection != 0, WmMaterial::getIsCollection, isCollection);

        // 查询当前用户
        wrapper.eq(WmMaterial::getUserId, WmUserThreadLocal.get().getId());

        // 构建排序条件
        wrapper.orderByDesc(WmMaterial::getCreatedTime);

        // 构建分页条件
        Page<WmMaterial> pageParam = new Page<>(page, size);
        Page<WmMaterial> pageResult = wmMaterialMapper.selectPage(pageParam, wrapper);

        // 构建返回结果
        Long total = pageResult.getTotal();
        PageResponseResult pageResponseResult = new PageResponseResult(page, size, total.intValue());
        pageResponseResult.setData(pageResult.getRecords());

        return pageResponseResult;
    }
}
